const timer = require('../../utils/timer.js')
var rec = wx.getRecorderManager()   //录音实例
var tempFilePath = null             //保存
var audioCtx = wx.createInnerAudioContext()  //播放录音实例
var noStopCallBack = null
const list = []

Page({
  data: {
    time:'00:00:00',
    state:0,
    recList:[]
  },
  rec:function(){
    switch(this.data.state){
      case 0:
        rec.start()
        timer.onTimeUpdate(time=>{
          this.setData({time})
        })
        timer.start()
        this.setData({time:'00:00:00',state:1})
        break
      case 1:
        rec.pause()
        timer.pause()
        this.setData({state:2})
        break
      case 2:
        rec.resume()
        timer.start()
        this.setData({state:1})
        break
    }
  },
  stop: function() {
    rec.stop()
    timer.reset()
    this.setData({ state: 0 ,time:'00:00:00'})
    rec.onStop(res=>{
      wx.showToast({
        title: '录音完成',
        icon: 'none',
        duration: 2000//持续的时间
      })
      tempFilePath = res.tempFilePath
      list.push(tempFilePath)
      this.setData({ recList: [...list] }) 
      noStopCallBack && noStopCallBack(tempFilePath)
    })
  },
  // 播放录音
  play:function(){
    if(this.data.state>0){
      // 
      noStopCallBack = tempFilePath=>{
        noStopCallBack=null
        audioCtx.src = tempFilePath
        audioCtx.play()
        this.setData({time:'播放录音'})
      }
      this.stop()
    }else if(tempFilePath){
      audioCtx.src=tempFilePath
      audioCtx.play()
      this.setData({time:'播放录音'})
      audioCtx.onEnded(()=>{
        wx.showToast({
          title: '播放完毕',
          icon: 'none',
          duration: 2000//持续的时间
        })
        this.setData({time:'00:00:00'})
      })
    }else{
      this.setData({time:'暂无录音'})
    }
  },
  appointPlay:function(e){
    if(this.data.state>0){
      wx.showToast({
        title: '您正在录音中无法播放语音哦请录音完毕后再播放',
        icon: 'none',
        duration: 2000//持续的时间
      })
    }else if(tempFilePath){
      audioCtx.src=this.data.recList[e.target.dataset.aid]
      audioCtx.play()
      this.setData({time:'播放录音'})
      audioCtx.onEnded(()=>{
        wx.showToast({
          title: '播放完毕',
          icon: 'none',
          duration: 2000//持续的时间
        })
        this.setData({time:'00:00:00'})
      })
    }else{
      this.setData({time:'暂无录音'})
    }
  }
})
